<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档管理</title>
    <!-- Element UI CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 自定义CSS -->
    <link rel="stylesheet" href="../css/style.css">
    <!-- Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <!-- Element UI JS -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <!-- API请求管理 -->
    <script src="../js/api.js"></script>
    <script>
        // 使用父窗口的全局变量
        const API_BASE_URL = window.parent.appGlobal.API_BASE_URL || '/api';
    </script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",Arial,sans-serif;
        }
        .component-container {
            padding: 15px;
        }
        .component-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .empty-state {
            text-align: center;
            padding: 40px 0;
            color: #909399;
        }
        .empty-state i {
            font-size: 50px;
        }
        .form-tip {
            font-size: 12px;
            color: #909399;
            margin-top: 5px;
        }
        .pagination-container {
            margin-top: 20px;
            text-align: center;
        }
        .document-content {
            white-space: pre-wrap;
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="component-container">
            <div class="component-header">
                <h3>文档管理{{ activeCollection ? ' - ' + activeCollection.name : '' }}</h3>
                <div>
                    <el-select 
                        v-model="selectedCollection" 
                        placeholder="切换集合" 
                        size="small" 
                        @change="switchCollection"
                        style="margin-right: 10px;">
                        <el-option
                            v-for="item in collections"
                            :key="item.name"
                            :label="item.name"
                            :value="item.name">
                            <span style="float: left">{{ item.name }}</span>
                            <span style="float: right; font-size: 12px; color: #8492a6; margin-right: 20px">
                                {{ item.document_count || 0 }}篇文档
                            </span>
                        </el-option>
                    </el-select>
                    <el-button 
                        type="primary" 
                        size="small" 
                        icon="el-icon-plus" 
                        @click="showAddDocumentDialog"
                        style="margin-right: 10px;">
                        添加文档
                    </el-button>
                    <el-button 
                        type="primary" 
                        size="small" 
                        icon="el-icon-upload2" 
                        @click="showBatchDocumentDialog"
                        style="margin-right: 10px;">
                        批量添加
                    </el-button>
                    <el-button 
                        type="danger" 
                        size="small" 
                        icon="el-icon-delete" 
                        @click="deleteAllDocuments">
                        清空文档
                    </el-button>
                </div>
            </div>
            
            <div v-if="!isActiveCollectionValid" class="empty-state">
                <i class="el-icon-folder"></i>
                <p>请先选择一个集合</p>
            </div>
            
            <div v-else-if="total === 0 && !loading" class="empty-state">
                <i class="el-icon-document"></i>
                <p>当前集合中没有文档，请添加文档</p>
            </div>
            
            <el-table
                v-else
                :data="documents"
                v-loading="loading"
                style="width: 100%">
                <el-table-column prop="id" label="ID" width="80"></el-table-column>
                <el-table-column label="内容">
                    <template slot-scope="scope">
                        {{ formatContent(scope.row.content) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            @click="viewDocument(scope.row)">
                            查看</el-button>
                        <el-button
                            size="mini"
                            type="danger"
                            @click="deleteDocument(scope.row)">
                            删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            
            <div class="pagination-container" v-if="total > 0">
                <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-size="pageSize"
                    layout="total, prev, pager, next"
                    :total="total">
                </el-pagination>
            </div>
            
            <!-- 添加文档对话框 -->
            <el-dialog title="添加文档" :visible.sync="dialogVisible" width="50%" @closed="resetForm('form')">
                <el-form :model="form" :rules="rules" ref="form" label-width="100px">
                    <el-form-item label="文档内容" prop="content">
                        <el-input
                            type="textarea"
                            :rows="10"
                            placeholder="请输入文档内容"
                            v-model="form.content">
                        </el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="createDocument" :loading="loading">确 定</el-button>
                </span>
            </el-dialog>
            
            <!-- 批量添加文档对话框 -->
            <el-dialog title="批量添加文档" :visible.sync="batchDialogVisible" width="60%" @closed="resetForm('batchForm')">
                <el-form :model="batchForm" :rules="batchRules" ref="batchForm" label-width="100px">
                    <el-form-item label="分隔符" prop="separator">
                        <el-input 
                            v-model="batchForm.separator" 
                            placeholder="输入用于分隔多个文档的字符串"
                            style="width: 300px;">
                        </el-input>
                        <div class="form-tip">每个分隔符之间的文本将作为一个独立的文档</div>
                    </el-form-item>
                    <el-form-item label="批量内容" prop="documents">
                        <el-input
                            type="textarea"
                            :rows="15"
                            placeholder="请输入批量文档内容，使用分隔符分隔每个文档"
                            v-model="batchForm.documents">
                        </el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="batchDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="batchCreateDocuments" :loading="loading">确 定</el-button>
                </span>
            </el-dialog>
            
            <!-- 查看文档对话框 -->
            <el-dialog title="文档详情" :visible.sync="viewDialogVisible" width="50%">
                <div v-if="currentDocument">
                    <p><strong>ID:</strong> {{ currentDocument.id }}</p>
                    <div class="document-content">{{ currentDocument.content }}</div>
                </div>
            </el-dialog>
        </div>
    </div>

    <script>
        // 页面脚本
        new Vue({
            el: '#app',
            data() {
                return {
                    documents: [],
                    total: 0,
                    loading: false,
                    currentPage: 1,
                    pageSize: 10,
                    dialogVisible: false,
                    viewDialogVisible: false,
                    batchDialogVisible: false,
                    currentDocument: null,
                    form: {
                        content: ''
                    },
                    batchForm: {
                        documents: '',
                        separator: '---'
                    },
                    rules: {
                        content: [
                            { required: true, message: '请输入文档内容', trigger: 'blur' }
                        ]
                    },
                    batchRules: {
                        documents: [
                            { required: true, message: '请输入批量文档内容', trigger: 'blur' }
                        ],
                        separator: [
                            { required: true, message: '请输入分隔符', trigger: 'blur' }
                        ]
                    },
                    selectedCollection: null,
                    collections: []
                };
            },
            computed: {
                // 从全局变量获取活动集合
                activeCollection() {
                    return window.parent.appGlobal.activeCollection;
                },
                isActiveCollectionValid() {
                    const collection = this.activeCollection;
                    return collection && collection.name;
                }
            },
            watch: {
                // 监听活动集合变化
                activeCollection: {
                    handler(newVal, oldVal) {
                        if ((!oldVal && newVal) || 
                            (oldVal && newVal && oldVal.name !== newVal.name)) {
                            this.currentPage = 1;
                            this.fetchDocuments();
                            // 同步selectedCollection和activeCollection
                            this.selectedCollection = newVal?.name;
                        }
                    },
                    deep: true,
                    immediate: true
                }
            },
            created() {
                // 初始时尝试获取文档
                if (this.isActiveCollectionValid) {
                    this.fetchDocuments();
                }
                this.fetchCollections();
            },
            methods: {
                // 获取文档列表
                fetchDocuments() {
                    if (!this.isActiveCollectionValid) return;
                    
                    this.loading = true;
                    const offset = (this.currentPage - 1) * this.pageSize;
                    
                    axios.get(`${API_BASE_URL}/documents?limit=${this.pageSize}&offset=${offset}`)
                        .then(response => {
                            this.documents = response.data.documents || [];
                            this.total = response.data.total || 0;
                        })
                        .catch(error => {
                            console.error('获取文档列表失败:', error);
                            this.$message.error('获取文档列表失败: ' + (error.response?.data?.error || error.message));
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                },
                
                // 创建文档
                createDocument() {
                    if (!this.isActiveCollectionValid) {
                        this.$message.warning('请先选择一个集合');
                        return;
                    }
                    
                    this.$refs.form.validate((valid) => {
                        if (valid) {
                            this.loading = true;
                            const data = { content: this.form.content };
                            
                            axios.post(`${API_BASE_URL}/documents`, data)
                                .then(response => {
                                    this.$message({
                                        message: '文档创建成功',
                                        type: 'success'
                                    });
                                    this.dialogVisible = false;
                                    this.form.content = '';
                                    this.fetchDocuments();
                                })
                                .catch(error => {
                                    console.error('创建文档失败:', error);
                                    this.$message.error('创建文档失败: ' + (error.response?.data?.error || error.message));
                                })
                                .finally(() => {
                                    this.loading = false;
                                });
                        }
                    });
                },
                
                // 批量添加文档
                batchCreateDocuments() {
                    if (!this.isActiveCollectionValid) {
                        this.$message.warning('请先选择一个集合');
                        return;
                    }
                    
                    this.$refs.batchForm.validate((valid) => {
                        if (valid) {
                            this.loading = true;
                            
                            // 使用分隔符拆分文本为多个文档
                            const contents = this.batchForm.documents.split(this.batchForm.separator);
                            const documents = contents
                                .map(content => content.trim())
                                .filter(content => content.length > 0)
                                .map(content => ({ content }));
                            
                            if (documents.length === 0) {
                                this.$message.warning('未找到有效的文档内容');
                                this.loading = false;
                                return;
                            }
                            
                            const data = { documents };
                            
                            axios.post(`${API_BASE_URL}/batch/documents`, data)
                                .then(response => {
                                    this.$message({
                                        message: `成功添加 ${response.data.created} 个文档`,
                                        type: 'success'
                                    });
                                    this.batchDialogVisible = false;
                                    this.batchForm.documents = '';
                                    this.fetchDocuments();
                                })
                                .catch(error => {
                                    console.error('批量添加文档失败:', error);
                                    this.$message.error('批量添加文档失败: ' + (error.response?.data?.error || error.message));
                                })
                                .finally(() => {
                                    this.loading = false;
                                });
                        }
                    });
                },
                
                // 查看文档详情
                viewDocument(document) {
                    this.currentDocument = document;
                    this.viewDialogVisible = true;
                },
                
                // 删除文档
                deleteDocument(document) {
                    this.$confirm('确定要删除该文档吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.loading = true;
                        axios.delete(`${API_BASE_URL}/documents/${document.id}`)
                            .then(() => {
                                this.$message({
                                    message: '文档删除成功',
                                    type: 'success'
                                });
                                this.fetchDocuments();
                            })
                            .catch(error => {
                                console.error('删除文档失败:', error);
                                this.$message.error('删除文档失败: ' + (error.response?.data?.error || error.message));
                            })
                            .finally(() => {
                                this.loading = false;
                            });
                    }).catch(() => {
                        // 取消删除操作
                    });
                },
                
                // 删除所有文档
                deleteAllDocuments() {
                    this.$confirm('此操作将删除所有文档，是否继续?', '警告', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                        distinguishCancelAndClose: true
                    }).then(() => {
                        this.loading = true;
                        axios.delete(`${API_BASE_URL}/documents`)
                            .then(response => {
                                this.$message({
                                    message: `成功删除 ${response.data.deleted} 个文档`,
                                    type: 'success'
                                });
                                this.fetchDocuments();
                            })
                            .catch(error => {
                                console.error('删除所有文档失败:', error);
                                this.$message.error('删除所有文档失败: ' + (error.response?.data?.error || error.message));
                            })
                            .finally(() => {
                                this.loading = false;
                            });
                    }).catch(() => {
                        // 取消删除操作
                    });
                },
                
                // 处理页码变更
                handleCurrentChange(page) {
                    this.currentPage = page;
                    this.fetchDocuments();
                },
                
                // 清空表单
                resetForm(formName) {
                    if (this.$refs[formName]) {
                        this.$refs[formName].resetFields();
                    }
                },
                
                // 格式化文档内容（截断）
                formatContent(content) {
                    if (!content) return '';
                    return content.length > 100 ? content.substr(0, 97) + '...' : content;
                },

                // 获取集合列表
                fetchCollections() {
                    axios.get(`${API_BASE_URL}/collections`)
                        .then(response => {
                            this.collections = response.data.collections || [];
                        })
                        .catch(error => {
                            console.error('获取集合列表失败:', error);
                            this.$message.error('获取集合列表失败: ' + (error.response?.data?.error || error.message));
                        });
                },

                // 切换集合
                switchCollection(collectionName) {
                    const collection = this.collections.find(item => item.name === collectionName);
                    if (collection) {
                        this.loading = true;
                        // 通知后端切换集合
                        axios.post(`${API_BASE_URL}/collections/${collectionName}/use`)
                            .then(() => {
                                // 更新父窗口全局变量
                                window.parent.appGlobal.activeCollection = collection;
                                
                                // 强制更新组件，确保标题刷新
                                this.$forceUpdate();
                                
                                this.$message({
                                    message: `已切换到集合: ${collection.name}`,
                                    type: 'success'
                                });
                                // 重置页码并刷新数据
                                this.currentPage = 1;
                                this.activeCollection.name = collection.name;
                                this.fetchDocuments();
                            })
                            .catch(error => {
                                console.error('切换集合失败:', error);
                                this.$message.error('切换集合失败: ' + (error.response?.data?.error || error.message));
                                // 回退选中的集合
                                this.selectedCollection = this.activeCollection?.name;
                            })
                            .finally(() => {
                                this.loading = false;
                            });
                    }
                },

                // 显示添加文档对话框
                showAddDocumentDialog() {
                    if (!this.isActiveCollectionValid) {
                        this.$message.warning('请先选择一个集合');
                        return;
                    }
                    this.dialogVisible = true;
                },

                // 显示批量添加文档对话框
                showBatchDocumentDialog() {
                    if (!this.isActiveCollectionValid) {
                        this.$message.warning('请先选择一个集合');
                        return;
                    }
                    this.batchDialogVisible = true;
                }
            }
        });
    </script>
</body>
</html>